import { createSlice } from "@reduxjs/toolkit";
import Taro from '@tarojs/taro'

const cartSlice = createSlice({
  name: "cart",
  initialState: {
    cartList: Taro.getStorageSync('cartList') || []
  },
  reducers: {
    addCartList(state, { payload }) {
      const item = state.cartList.find(v => v.id === payload.id);
      if(item) {
        item.count++
      } else {
        state.cartList.push(payload)
      };
      Taro.setStorageSync('cartList', state.cartList)
    },
    changeCartList(state, { payload }) {
      const item = state.cartList.find(v => v.id === payload.id);
      item.count = payload.count
      Taro.setStorageSync('cartList', state.cartList)
    },
    changeState(state, { payload }) {
      const item = state.cartList.find(v => v.id === payload.id);
      item.state = !item.state
      Taro.setStorageSync('cartList', state.cartList)
    },
    deleteCartList(state, { payload }) {
      state.cartList = state.cartList.filter(v => v.id !== payload.id)
      Taro.setStorageSync('cartList', state.cartList)
    }
  },
});

export default cartSlice;
export const { addCartList,changeCartList, changeState, deleteCartList } = cartSlice.actions
